package com.asynctm.android.tm.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import android.os.Environment;

import com.asynctm.android.common.exception.DaoException;
import com.asynctm.android.tm.dto.ActivityDto;

/**
 * Implementa {@link TaskDao}
 * 
 * @author rockdrigo
 */
public class TaskDaoImpl implements TaskDao {

	@Override
	public List<ActivityDto> getTask(String path) throws DaoException {
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File (sdCard.getAbsolutePath() + "/ATM");
		dir.mkdirs();
		File file = new File(dir, path);
		LinkedList<ActivityDto> activities = new LinkedList<ActivityDto>();
		try {
		    BufferedReader br = new BufferedReader(new FileReader(file));
		    String line;
		    while ((line = br.readLine()) != null) {
		    	ActivityDto activityDto = new ActivityDto(); 
		    	String[] args = line.split(",");
		    	activityDto.setActivityName(args[0]);
		    	activityDto.setActivityDescription(args[1]);
		    	activityDto.setActivityDate(args[2]);
		        activities.add(activityDto);
		    }
		} catch (Exception e) {
			e.printStackTrace();
			writeTask(activities, path);
		}
		
		return activities;
	}

	@Override
	public void writeTask(LinkedList<ActivityDto> activities, String path) throws DaoException {	
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File (sdCard.getAbsolutePath() + "/ATM");
		dir.mkdirs();
		File file = new File(dir, path);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			PrintWriter printWriter = new PrintWriter(fos);
			while (!activities.isEmpty()) {
				printWriter.print(activities.poll().toString() + "\n");
			}
			printWriter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new DaoException(e);
		}
		
	}
	
}
